package publish

import (
	"context"
	"encoding/json"
	"group-card/common/response"
	"group-card/rpc/card/cardclient"

	"group-card/api/internal/svc"
	"group-card/api/internal/types"

	"github.com/zeromicro/go-zero/core/logx"
)

type PublishAddLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewPublishAddLogic(ctx context.Context, svcCtx *svc.ServiceContext) *PublishAddLogic {
	return &PublishAddLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *PublishAddLogic) PublishAdd(req *types.AddPublishRequest) (resp *types.PublishResponse, err error) {

	if req.EndNumber <= req.BeginNumber {
		return &types.PublishResponse{Code: response.ErrCode, Message: "起止卡片序列号不对"}, nil
	}

	if req.EndNumber-req.BeginNumber != req.Count-1 {
		return &types.PublishResponse{Code: response.ErrCode, Message: "卡片数量不对"}, nil
	}

	data, err := l.svcCtx.Card.PublishAdd(l.ctx, &cardclient.PublishAddRequest{
		PublishTime:        req.PublishTime,
		AdminId:            req.AdminId,
		CustomerId:         req.CustomerId,
		SkinId:             req.SkinId,
		Count:              req.Count,
		BeginNumber:        req.BeginNumber,
		EndNumber:          req.EndNumber,
		Status:             req.Status,
		Type:               req.Type,
		ServiceNumber:      req.ServiceNumber,
		ServiceOrderNumber: req.ServiceOrderNumber,
		ServiceMoney:       req.ServiceMoney,
	})

	if err != nil {
		reqStr, _ := json.Marshal(req)
		logx.WithContext(l.ctx).Errorf("添加卡片发行失败,参数:%s,异常:%s", reqStr, err.Error())
		return &types.PublishResponse{Code: response.ErrCode, Message: response.StrErr(err.Error())}, nil
	}

	return &types.PublishResponse{
		Code:    response.SuccessCode,
		Message: "添加卡片发行成功",
		Data:    data.Id,
	}, nil

}
